// 权限控制
// 1.路由跳转权限控制
// 2.菜单权限控制
import router from '@/router'

import { getToken } from '@/utils/auth'
// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from './store'

const WHITELIST = ['/login', '/404']

router.beforeEach((to, from, next) => {
  // to and from are both route objects. must call `next`.
  const token = getToken()

  // 开启进度条
  NProgress.start()
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()

      // 在此处获取用户信息
      // 首先要判断是否已经存在用户信息，如果存在不用重复发起请求
      if (!store.state.user.userInfo.userId) {
        store.dispatch('user/fetchUserInfo')
      }
    }
  } else {
    if (WHITELIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  // 关闭进度条
  NProgress.done()
})
